package com.wdy.action;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.excelutils.ExcelUtils;

import com.wdy.po.User;
import com.wdy.service.UserManager;

@SuppressWarnings({"serial", "unused"})
public class ExcelAction extends BasicAction {

	private Map<String, Object> session;
	private HttpServletResponse response;
	private HttpServletRequest request;
	private ServletContext servletContext;
	private User user;
	private UserManager userManager;
	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public String export() throws Exception{
		List<User> list = null;
		list = (List<User>) userManager.listAll();
		user = new User();
		user.setUsername("username");
		user.setPassword("password");
		ExcelUtils.addValue("user", user);
		ExcelUtils.addValue("test", "test");
		ExcelUtils.addValue("printDate", getCurrentDate("yyyy-MM-dd"));
		ExcelUtils.addValue("list", list);
		
		response.reset();
		String config = "/excel/template.xls";
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + System.currentTimeMillis() + ".xls\"");
		OutputStream out = response.getOutputStream();
		ExcelUtils.export(servletContext, config, out);
		out.close();
		return SUCCESS;
	}
	
	protected String getCurrentDate(String pattern) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.format(new Date());
	}

}
